package org.rainwalk.library.api.auth;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.rainwalk.library.api.exception.BizException;
import org.rainwalk.library.api.model.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 接口权限校验代理
 *
 * @author 趁雨行 2021-07-22 16:39:10
 */
@Aspect
@Component
@RequiredArgsConstructor(onConstructor_={@Autowired})
public class AuthDelegate {

    private final AuthProperties authProperties;

    @Before("@annotation(org.rainwalk.library.api.auth.Auth)")
    private void before() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String token = request.getHeader("LIBRARY|TOKEN");
        if (StrUtil.isBlank(token)) {
            throw new BizException(ResponseCode.UNAUTHORIZED);
        }
        boolean verify;
        try {
            verify = JWT.of(token)
                    .setKey(authProperties.getKey().getBytes())
                    .verify();
        } catch (JWTException e) {
            throw new BizException(ResponseCode.UNAUTHORIZED);
        }
        if (!verify) {
            throw new BizException(ResponseCode.UNAUTHORIZED);
        }
    }
}
